package mall.filter;


import mall.core.ApplicationProperties;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static mall.core.session.SessionKey.LOGIN_USER;

public class AuthenticationFilter implements Filter {

    private static final List<String> exclude = new ArrayList<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        exclude.add("/client/product");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse res = (HttpServletResponse) servletResponse;

        String path = req.getServletPath();

        if (needExclude(path)) {
            System.out.println("[无需拦截，放行] " + path);
            filterChain.doFilter(req, res);
            return;
        }

        HttpSession session = req.getSession();
        if (session == null || session.getAttribute(LOGIN_USER) == null) {
            System.out.println("[未登录，跳转登录页面] " + path);
            req.getRequestDispatcher(req.getContextPath() + ApplicationProperties.VIEW_PREFIX + "/login" + ApplicationProperties.VIEW_SUFFIX).forward(req, res);
            return;
        }

        System.out.println("[已登录，放行] " + path);
        filterChain.doFilter(req, res);
    }

    private boolean needExclude(String path) {
        if (exclude.contains(path)) {
            return true;
        }

        return false;
    }

    @Override
    public void destroy() {
    }
}